/**
 * @description 
 * @project: GPSTracker
 * @Date:2016-07-25
 * @Company: xexun
 * @author tfx
 */
package com.xexun.gpstracker.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.component.MessageSender;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.User;
import com.xexun.gpstracker.service.CommunicationService;
import com.xexun.gpstracker.ui.LoginActivity;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.IMEI;
import com.xexun.gpstracker.util.JSONHelper;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.FlavorType;
import com.xexun.gpstracker.vo.Session;

import java.util.List;

/**
 * &#x5f00;&#x673a;&#x81ea;&#x542f;&#x52a8;&#x63a5;&#x6536;&#x5668;
 * @project: GpsTracker
 * @Date: 2016-07-25
 * @Company: xexun
 * @author: tfx
 */
public class PowerOnReceiver extends BroadcastReceiver{
	private SharedPreferences mSharedPreferences;
    private Context mContext = null;
	@Override
	public void onReceive(Context context, Intent intent) {
		if(Constants.powerOnStart)
			return;
		Constants.powerOnStart = true;
		mContext = context;
		initExtraData();

		Log.i(Constants.TAG, "接收到开机广播");
		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) && Constants.FLAVOR  == FlavorType.PHONELOC){
			mSharedPreferences = Utils.getPreferences(context);
			Constants.baseUrl = Utils.getBaseUrl(context);
			String savedPhone = mSharedPreferences.getString(MyConstants.USER_PHONE, "");
			String savedPsd = mSharedPreferences.getString(MyConstants.USER_PWD, "");
			if(CommUtil.isBlank(savedPhone) || CommUtil.isBlank(savedPsd)) {
				Intent login_intent = new Intent();
				login_intent.setClass(context, LoginActivity.class);
				login_intent.putExtra("itemData", "powneron");
			    login_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Log.i(Constants.TAG, "未保存账户，进入登录界面");
				context.startActivity(login_intent);
			} else {
				Log.i(Constants.TAG, "已登录过，开启后台监听服务");
				Constants.baseUrl = Utils.getBaseUrl(context);
				//初始化缓存环境
				Session.getInstance().clearData();
				initExtraData();
				Log.i(Constants.TAG, "登录imei：" + Session.getInstance().getClientId());
				login(savedPhone, savedPsd);
			}
		}
		return;
	}

	private void login(final String phone, final String pwd) {
		Log.i(Constants.TAG, "开始登录:" + phone + "," + pwd);
		User.login(mContext, phone, pwd, new HttpCallback() {
			@Override
			public void onStart() {
				//WizardAlertDialog.getInstance().showProgressDialog(R.string.login_post_data, LoginActivity.this);
			}

			@Override
			public void onFinish() {

			}

			@Override
			public void onSuccess(ResponseData obj) {
				if (obj.getRetcode() == 1) {
                            /*------------*/
					//Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
					Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
					User user = new User();
					user.setId(JSONHelper.getLong(obj.getBody(), "id"));
					user.setPhone(phone);
					user.setAppUserNum(JSONHelper.getString(obj.getBody(), "appUserNum"));
					user.setImei(obj.getBodyString("imei"));
					Session.getInstance().setUser(user);
					Session.getInstance().setImei(user.getImei());

					AppContext.termType = JSONHelper.getInt(obj.getBody(), "type");

				/*	Intent mainIntent = new Intent(mContext, MainActivity.class);
					mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Toast.makeText(mContext, "start main activity", Toast.LENGTH_LONG).show();
					mContext.startActivity(mainIntent);*/
					AppContext.isEntered = true;
					Intent service = new Intent();
					service.setClass(mContext, CommunicationService.class);
					mContext.startService(service);
					Log.i(Constants.TAG, "开机定位");
                    MainActivity.getLocationEx();
					//LoginActivity.this.finish();
				} else if (CommUtil.isNotBlank(obj.getMsg())) {
					Log.i(Constants.TAG, "登录失败:" + "getRetcode not 1");
					//Toast.makeText(LoginActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onFailure(String message) {
				Log.i(Constants.TAG, "登录失败:" + message);
				//WizardAlertDialog.getInstance().closeProgressDialog();
				//Toast.makeText(LoginActivity.this, R.string.login_err, Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void initExtraData() {
		List<String> imeis = IMEI.getIMEI(mContext);
		if (CommUtil.isNotEmpty(imeis)) {
			Session.getInstance().setClientId(imeis.get(0));
		}
	}
}
